# -*- coding: utf-8 -*-

import re
from PySide2.QtGui import QColor
from typing import Union, Tuple, Optional

class ColorConverter:
    """
    颜色转换器，支持多种颜色格式的解析和转换
    支持格式：rgba, hex, rgb, hsl, hwb, lch, cmyk, name等
    """
    
    # 预定义的颜色名称映射
    COLOR_NAMES = {
        'black': (0, 0, 0),
        'white': (255, 255, 255),
        'red': (255, 0, 0),
        'green': (0, 128, 0),
        'blue': (0, 0, 255),
        'yellow': (255, 255, 0),
        'cyan': (0, 255, 255),
        'magenta': (255, 0, 255),
        'gray': (128, 128, 128),
        'grey': (128, 128, 128),
        'orange': (255, 165, 0),
        'purple': (128, 0, 128),
        'brown': (165, 42, 42),
        'pink': (255, 192, 203),
        'lime': (0, 255, 0),
        'navy': (0, 0, 128),
        'maroon': (128, 0, 0),
        'olive': (128, 128, 0),
        'teal': (0, 128, 128),
        'silver': (192, 192, 192),
        'gold': (255, 215, 0),
        'transparent': (0, 0, 0, 0)
    }
    
    @staticmethod
    def parse_color(color_str: str) -> Optional[Tuple[int, int, int, int]]:
        """
        解析颜色字符串，返回RGBA元组 (r, g, b, a)
        
        Args:
            color_str: 颜色字符串
            
        Returns:
            RGBA元组 (r, g, b, a)，如果解析失败返回None
        """
        if not isinstance(color_str, str):
            return None
            
        color_str = color_str.strip().lower()
        
        # 处理颜色名称
        if color_str in ColorConverter.COLOR_NAMES:
            rgb = ColorConverter.COLOR_NAMES[color_str]
            if len(rgb) == 3:
                return rgb + (255,)  # 添加alpha通道
            return rgb
        
        # 处理十六进制颜色 (#RGB, #RRGGBB, #RRGGBBAA)
        hex_match = re.match(r'^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$', color_str)
        if hex_match:
            hex_color = hex_match.group(1)
            if len(hex_color) == 3:
                # #RGB -> #RRGGBB
                r = int(hex_color[0] * 2, 16)
                g = int(hex_color[1] * 2, 16)
                b = int(hex_color[2] * 2, 16)
                return (r, g, b, 255)
            elif len(hex_color) == 6:
                # #RRGGBB
                r = int(hex_color[0:2], 16)
                g = int(hex_color[2:4], 16)
                b = int(hex_color[4:6], 16)
                return (r, g, b, 255)
            elif len(hex_color) == 8:
                # #RRGGBBAA
                r = int(hex_color[0:2], 16)
                g = int(hex_color[2:4], 16)
                b = int(hex_color[4:6], 16)
                a = int(hex_color[6:8], 16)
                return (r, g, b, a)
        
        # 处理RGB格式 rgb(r, g, b)
        rgb_match = re.match(r'^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$', color_str)
        if rgb_match:
            r, g, b = map(int, rgb_match.groups())
            return (r, g, b, 255)
        
        # 处理RGBA格式 rgba(r, g, b, a)
        rgba_match = re.match(r'^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([0-9.]+)\s*\)$', color_str)
        if rgba_match:
            r, g, b = map(int, rgba_match.groups()[:3])
            a = float(rgba_match.group(4))
            # 如果alpha是0-1范围，转换为0-255
            if a <= 1.0:
                a = int(a * 255)
            else:
                a = int(a)
            return (r, g, b, a)
        
        # 处理分号分隔的RGB格式 "255; 255; 255"
        semicolon_match = re.match(r'^(\d+)\s*;\s*(\d+)\s*;\s*(\d+)(?:\s*;\s*(\d+))?$', color_str)
        if semicolon_match:
            r, g, b = map(int, semicolon_match.groups()[:3])
            a = int(semicolon_match.group(4)) if semicolon_match.group(4) else 255
            return (r, g, b, a)
        
        # 处理HSL格式 hsl(h, s%, l%)
        hsl_match = re.match(r'^hsl\s*\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$', color_str)
        if hsl_match:
            h, s, l = map(int, hsl_match.groups())
            rgb = ColorConverter._hsl_to_rgb(h, s / 100.0, l / 100.0)
            return rgb + (255,)
        
        return None
    
    @staticmethod
    def _hsl_to_rgb(h: int, s: float, l: float) -> Tuple[int, int, int]:
        """
        将HSL颜色转换为RGB
        
        Args:
            h: 色相 (0-360)
            s: 饱和度 (0-1)
            l: 亮度 (0-1)
            
        Returns:
            RGB元组 (r, g, b)
        """
        h = h / 360.0
        
        def hue_to_rgb(p, q, t):
            if t < 0:
                t += 1
            if t > 1:
                t -= 1
            if t < 1/6:
                return p + (q - p) * 6 * t
            if t < 1/2:
                return q
            if t < 2/3:
                return p + (q - p) * (2/3 - t) * 6
            return p
        
        if s == 0:
            r = g = b = l  # 灰度
        else:
            q = l * (1 + s) if l < 0.5 else l + s - l * s
            p = 2 * l - q
            r = hue_to_rgb(p, q, h + 1/3)
            g = hue_to_rgb(p, q, h)
            b = hue_to_rgb(p, q, h - 1/3)
        
        return (int(r * 255), int(g * 255), int(b * 255))
    
    @staticmethod
    def to_qcolor(color_input: Union[str, Tuple, QColor]) -> QColor:
        """
        将颜色输入转换为QColor对象
        
        Args:
            color_input: 颜色输入（字符串、元组或QColor对象）
            
        Returns:
            QColor对象
        """
        if isinstance(color_input, QColor):
            return color_input
        
        if isinstance(color_input, (list, tuple)):
            if len(color_input) >= 3:
                r, g, b = color_input[:3]
                a = color_input[3] if len(color_input) > 3 else 255
                return QColor(int(r), int(g), int(b), int(a))
        
        if isinstance(color_input, str):
            rgba = ColorConverter.parse_color(color_input)
            if rgba:
                return QColor(rgba[0], rgba[1], rgba[2], rgba[3])
        
        # 默认返回黑色
        return QColor(0, 0, 0)
    
    @staticmethod
    def to_rgb_string(color_input: Union[str, Tuple, QColor]) -> str:
        """
        将颜色输入转换为RGB字符串格式
        
        Args:
            color_input: 颜色输入（字符串、元组或QColor对象）
            
        Returns:
            RGB字符串格式 "rgb(r, g, b)"
        """
        qcolor = ColorConverter.to_qcolor(color_input)
        return f"rgb({qcolor.red()}, {qcolor.green()}, {qcolor.blue()})"
    
    @staticmethod
    def to_rgba_string(color_input: Union[str, Tuple, QColor]) -> str:
        """
        将颜色输入转换为RGBA字符串格式
        
        Args:
            color_input: 颜色输入（字符串、元组或QColor对象）
            
        Returns:
            RGBA字符串格式 "rgba(r, g, b, a)"
        """
        qcolor = ColorConverter.to_qcolor(color_input)
        alpha = qcolor.alpha() / 255.0
        return f"rgba({qcolor.red()}, {qcolor.green()}, {qcolor.blue()}, {alpha:.2f})"
    
    @staticmethod
    def to_hex_string(color_input: Union[str, Tuple, QColor]) -> str:
        """
        将颜色输入转换为十六进制字符串格式
        
        Args:
            color_input: 颜色输入（字符串、元组或QColor对象）
            
        Returns:
            十六进制字符串格式 "#RRGGBB"
        """
        qcolor = ColorConverter.to_qcolor(color_input)
        return f"#{qcolor.red():02x}{qcolor.green():02x}{qcolor.blue():02x}"
    
    @staticmethod
    def to_pyqtgraph_format(color_input: Union[str, Tuple, QColor]):
        """
        将颜色输入转换为pyqtgraph支持的格式
        
        Args:
            color_input: 颜色输入（字符串、元组或QColor对象）
            
        Returns:
            pyqtgraph支持的颜色格式（RGB元组或十六进制字符串）
        """
        qcolor = ColorConverter.to_qcolor(color_input)
        # 返回RGB元组格式，这是pyqtgraph mkColor支持的格式
        return (qcolor.red(), qcolor.green(), qcolor.blue())
    
    @staticmethod
    def convert_color_to_rgba(color_str: str, alpha: float = 1.0) -> Tuple[float, float, float, float]:
        """
        将颜色字符串转换为RGBA元组（0-1范围）
        
        Args:
            color_str: 颜色字符串
            alpha: 透明度值（0-1范围）
            
        Returns:
            RGBA元组，值范围为0-1
        """
        try:
            # 解析颜色字符串
            rgba = ColorConverter.parse_color(color_str)
            if rgba:
                # 转换为0-1范围
                r = rgba[0] / 255.0
                g = rgba[1] / 255.0
                b = rgba[2] / 255.0
                a = alpha  # 使用传入的alpha值
                return (r, g, b, a)
            else:
                # 默认返回白色
                return (1.0, 1.0, 1.0, alpha)
        except Exception:
            # 出错时返回白色
            return (1.0, 1.0, 1.0, alpha)